using System.IO;
using System.Xml;
using System.Xml.Xsl;

namespace EnhancedCQWP.EnhancedContentQuery
{
    public class XmlToXsltTransformer
    {
        public string GetHtml(string xml, string xslt)
        {
            var sw = new StringWriter();

            var xrt = XmlReader.Create(new StringReader(xslt));
            var xri = XmlReader.Create(new StringReader(xml));

            var xmlWriterSettings = new XmlWriterSettings
            {
                OmitXmlDeclaration = true,
                ConformanceLevel = ConformanceLevel.Fragment,
                CloseOutput = false
            };

            var xslArgs = new XsltArgumentList();
            var runtime = new DdwRuntime();
            xslArgs.AddExtensionObject("http://schemas.microsoft.com/WebParts/v2/DataView/runtime", runtime);

            using (XmlWriter xwo = XmlWriter.Create(sw, xmlWriterSettings))
            {
                var xsltTrans = new XslCompiledTransform();
                xsltTrans.Load(xrt);
                xsltTrans.Transform(xri, xslArgs, xwo);
            }

            return sw.ToString();
        } 
    }
}